<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="分类名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="分类名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" width="95">
        <template slot-scope="scope">
          {{ scope.row.sort }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 分类表单弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form ref="categoryForm" :model="categoryForm" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'

export default {
  name: 'CarCategory',
  components: { Pagination },
  data() {
    return {
      // 模拟数据
      mockCategories: [
        {
          id: 1,
          name: '轿车',
          description: '标准家用轿车',
          sort: 1,
          createTime: '2024-01-10 12:00:00'
        },
        {
          id: 2,
          name: 'SUV',
          description: '运动型多用途车',
          sort: 2,
          createTime: '2024-01-10 12:00:00'
        },
        {
          id: 3,
          name: '新能源',
          description: '电动汽车及混合动力',
          sort: 3,
          createTime: '2024-01-10 12:00:00'
        }
      ],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      dialogVisible: false,
      dialogTitle: '',
      categoryForm: {
        id: undefined,
        name: '',
        description: '',
        sort: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      setTimeout(() => {
        let filteredCategories = [...this.mockCategories]
        if (this.listQuery.name) {
          filteredCategories = filteredCategories.filter(category => 
            category.name.includes(this.listQuery.name)
          )
        }
        
        const start = (this.listQuery.page - 1) * this.listQuery.limit
        const end = start + this.listQuery.limit
        
        this.list = filteredCategories.slice(start, end)
        this.total = filteredCategories.length
        this.listLoading = false
      }, 500)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCreate() {
      this.dialogTitle = '新增分类'
      this.categoryForm = {
        id: undefined,
        name: '',
        description: '',
        sort: 0
      }
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.dialogTitle = '编辑分类'
      this.categoryForm = Object.assign({}, row)
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该分类吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const index = this.mockCategories.findIndex(category => category.id === row.id)
        if (index > -1) {
          this.mockCategories.splice(index, 1)
          this.$message.success('删除成功')
          this.getList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分类失败:', error)
        }
      }
    },
    submitForm() {
      this.$refs.categoryForm.validate(valid => {
        if (valid) {
          const now = new Date().toLocaleString()
          if (this.categoryForm.id) {
            const index = this.mockCategories.findIndex(category => category.id === this.categoryForm.id)
            if (index > -1) {
              this.mockCategories[index] = { 
                ...this.categoryForm,
                createTime: this.mockCategories[index].createTime
              }
              this.$message.success('更新成功')
            }
          } else {
            const newCategory = {
              ...this.categoryForm,
              id: this.mockCategories.length + 1,
              createTime: now
            }
            this.mockCategories.push(newCategory)
            this.$message.success('创建成功')
          }
          this.dialogVisible = false
          this.getList()
        }
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
  margin-right: 10px;
}
</style>